package com.ljxt.dt.util.xhq;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 徐浩钦
 * @version 1.0.0
 * @date 2020/5/2 10:52
 * @copyright 老九学堂T11
 */
public class ViewUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    private static String prefix = "/WEB-INF/views/";
    private static String suffix = ".jsp";
    private static String root = "/";

    private static String parseViewName(String viewName) {
        return prefix + viewName + suffix;
    }

    public static void forward(HttpServletRequest request, HttpServletResponse response, String viewName) throws ServletException, IOException {
        request.getRequestDispatcher(parseViewName(viewName)).forward(request, response);
    }

    public static void redirect(HttpServletRequest request, HttpServletResponse response, String viewName) throws IOException {
        if(!viewName.startsWith(root)){
            throw new RuntimeException(viewName + "必须已 / 开头");
        }
        response.sendRedirect(request.getContextPath() + viewName);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValueAsString(new Object());
    }

    /**
     * 阿贾克斯的重定向
     * @param response 响应的对象
     * @param obj 相应的数据
     * @param <T> 类型
     */
    public static void ajaxRedirect(HttpServletResponse response, Object obj){
        try {
            response.getWriter().write(objectMapper.writeValueAsString(obj));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
